package com.example.idlefish.HomeAndSearch

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.idlefish.GoodsInfo.ActivityContract.GooddResultContract
import com.example.idlefish.GoodsInfo.pojo.Class_t
import com.example.idlefish.PublicModule.NetworkSettings
import com.example.idlefish.R
import org.json.JSONArray
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.CopyOnWriteArrayList

class OneResultActivity: AppCompatActivity() {
    val goodContentLauncher = registerForActivityResult(GooddResultContract()){
            result->
        if(result)
        {
            // Toast.makeText(this, "成功从详情页返回", Toast.LENGTH_LONG).show()

        }
        else{
            // Toast.makeText(this, "详情页返回失败", Toast.LENGTH_LONG).show()
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.one_result) // 引用布局文件

        val receivedString = intent.getStringExtra("name")
        val type = intent.getStringExtra("type")
        println(receivedString)
        val search_txt = findViewById<EditText>(R.id.search_txt)
        val targetTextView = findViewById<TextView>(R.id.targetTextView)

        val search_button = findViewById<Button>(R.id.search_button)
        if (receivedString != null) {
            // 使用传入的字符串
            search_txt.setText(receivedString)
        }

        val productList: MutableList<ProductInfo> = mutableListOf()
        val RecycleGoods1 = findViewById<RecyclerView>(R.id.RecycleGoods1)
        val RecycleGoods2 = findViewById<RecyclerView>(R.id.RecycleGoods2)
        RecycleGoods1.setHasFixedSize(true)
        // 设置布局管理器
        RecycleGoods1.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        RecycleGoods2.setHasFixedSize(true)
        // 设置布局管理器
        RecycleGoods2.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)


        if(type == "1")
        {

            val ClassList = mutableListOf<Class_t>()
            Thread {
                try {
                    val urlString = "${NetworkSettings.HTTP}/product/getclass"
                    val url = URL(urlString)
                    val conn = url.openConnection() as HttpURLConnection
                    conn.requestMethod = "GET"

                    val reader = BufferedReader(InputStreamReader(conn.inputStream), 8192)
                    val response = StringBuilder()
                    var line: String?
                    while (reader.readLine().also { line = it } != null) {
                        response.append(line)
                    }
                    reader.close()
                    val jsonArray = JSONArray(response.toString())
                    for (i in 0 until jsonArray.length()) {
                        val obj = jsonArray.getJSONObject(i)
                        val id = obj.getInt("id")
                        val name = obj.getString("name")
                        ClassList.add(
                            Class_t(
                                id = id,
                                name = name
                            )
                        )
                    }
                    runOnUiThread {



                        val matchingId = ClassList.firstOrNull { it.name == receivedString }?.id

                        if (matchingId != null) {
                            getlist(productList, RecycleGoods1, RecycleGoods2,receivedString,1, matchingId, targetTextView)

                        } else {
                            println("No matching ID found!")
                        }
                    }

                } catch (e: Exception) {
                    Log.e("Product", "Exception occurred: ${e.message}", e)
                }

            }.start()
        }
        else
        {
            getlist(productList, RecycleGoods1, RecycleGoods2, receivedString, 0, 0, targetTextView)
        }


        search_button.setOnClickListener{
            if (!search_button.text.isNullOrEmpty()) {

                val st = search_txt.text.toString()
                getlist(productList, RecycleGoods1, RecycleGoods2, st, 0, 0, targetTextView)
            }
        }

    }

    var isSyncing = false
    fun setupSyncedRecyclerViews(recyclerView1: RecyclerView, recyclerView2: RecyclerView) {
        // Variable to prevent infinite loop
        var isSyncing = false

        // Scroll listener to handle sync
        val scrollListener = object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                if (isSyncing) return
                isSyncing = true

                if (recyclerView === recyclerView1) {
                    syncScroll(recyclerView1, recyclerView2)
                } else if (recyclerView === recyclerView2) {
                    syncScroll(recyclerView2, recyclerView1)
                }

                isSyncing = false
            }
        }

        // Add the scroll listener to both RecyclerViews
        recyclerView1.addOnScrollListener(scrollListener)
        recyclerView2.addOnScrollListener(scrollListener)
    }

    // Helper function to sync scroll offset
    private fun syncScroll(source: RecyclerView, target: RecyclerView) {
        val sourceLayoutManager = source.layoutManager as? LinearLayoutManager ?: return
        val targetLayoutManager = target.layoutManager as? LinearLayoutManager ?: return

        // Get the first visible item's position and offset in the source RecyclerView
        val firstVisiblePosition = sourceLayoutManager.findFirstVisibleItemPosition()
        val firstVisibleView = sourceLayoutManager.findViewByPosition(firstVisiblePosition) ?: return
        val offset = firstVisibleView.top - source.paddingTop

        // Scroll the target RecyclerView to the same position and offset
        targetLayoutManager.scrollToPositionWithOffset(firstVisiblePosition, offset)
    }
    fun getlist(productList:MutableList<ProductInfo>,
                RecycleGoods1: RecyclerView,
                RecycleGoods2: RecyclerView,
                temp:String?,
                kind:Int?,
                cl:Int?,
                targetTextView: TextView)
    {
        Thread {
            try {
                var urlString:String
                if(kind == 0)
                {
                    urlString = "${NetworkSettings.HTTP}/product/getOnetypeGood?kind=${temp}"
                }
                else{
                    urlString = "${NetworkSettings.HTTP}/product/getOnetype?kind=${cl}"
                }
                val url = URL(urlString)
                val conn = url.openConnection() as HttpURLConnection
                conn.requestMethod = "GET"

                val reader = BufferedReader(InputStreamReader(conn.inputStream), 8192)
                val response = StringBuilder()
                var line: String?
                while (reader.readLine().also { line = it } != null) {

                    response.append(line)
                }
                reader.close()
                productList.clear()
                val jsonArray = JSONArray(response.toString())
                for (i in 0 until jsonArray.length()) {
                    val obj = jsonArray.getJSONObject(i)
                    val id = obj.getInt("id")
                    val name = obj.getString("name")
                    val info = obj.getString("text")
                    val address = obj.getString("address")
                    val price = obj.getDouble("price")
                    val wanting = obj.getInt("wanting")
                    val cut = obj.getInt("cut")
                    val advantage = obj.getString("advantage")
                    productList.add(
                        ProductInfo(
                            id = id,
                            name = name,
                            text = info,
                            price = price,
                            wanting = wanting,
                            advantage = advantage,
                            address = address,
                            cut = cut
                        )
                    )
                }

                // 在主线程中更新 UI
                runOnUiThread {

                    // 检查数据值
                    if (productList.size == 0) {
                        targetTextView.visibility = View.VISIBLE // 数据为0，显示TextView
                    } else {
                        targetTextView.visibility = View.GONE // 数据不为0，隐藏TextView
                        val (firstList, secondList) = if (productList.size < 4) {
                            // 如果 productList 的大小小于 4，直接不拆分
                            val middle = productList.size / 2
                            Pair(
                                CopyOnWriteArrayList(productList.subList(0, middle)),
                                CopyOnWriteArrayList(productList.subList(middle, productList.size))
                            )
                        } else {
                            // 如果 productList 的大小大于等于 4，执行拆分并处理奇数情况
                            val adjustedSize = if (productList.size % 2 != 0) productList.size - 1 else productList.size
                            val middle = adjustedSize / 2
                            Pair(
                                CopyOnWriteArrayList(productList.subList(0, middle)),
                                CopyOnWriteArrayList(productList.subList(middle, adjustedSize))
                            )
                        }

                        val adapter1 = GoodsAdapater(secondList, { itemId ->
                            println("Clicked item: $itemId")
                            goodContentLauncher.launch(itemId.toLong())
                        }, RecycleGoods1)
                        RecycleGoods1.adapter = adapter1

                        val adapter2 = GoodsAdapater(firstList, { itemId ->
                            println("Clicked item: $itemId")
                            goodContentLauncher.launch(itemId.toLong())
                        }, RecycleGoods2)
                        RecycleGoods2.adapter = adapter2
                        setupSyncedRecyclerViews(RecycleGoods1, RecycleGoods2)
                    }

                }

            } catch (e: Exception) {
                Log.e("Product", "Exception occurred: ${e.message}", e)
            }
        }.start()
    }
}